package com.lingchen.boot.controller;

import com.lingchen.boot.utils.CSVUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lc on 2019/1/2
 */
@Controller
@RequestMapping("/csv")
public class CsvController {
    @RequestMapping("")
    public String page() {
        return "csvPage";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public Object upload(MultipartHttpServletRequest multipartRequst) {
        HashMap<Object, Object> result = new HashMap<>();
        MultipartFile file = multipartRequst.getFile("file_data");
        if (null == file) {
            return "不允许上传文件为空";
        }
        String name = file.getOriginalFilename();
        if (StringUtils.isEmpty(name) || !StringUtils.contains(name, ".csv")) {
            return "文件必须为csv格式";
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<String[]> dataList = CSVUtils.importCsv((FileInputStream) inputStream,"UTF-8");
        String validate = dataList.get(0)[0];
        if (!StringUtils.contains(validate,"类型")){
            return "模板格式错误";
        }
        if (dataList != null && !dataList.isEmpty()) {
            for (String[] data : dataList) {
                for (String in : data) {
                    System.out.print(in + "-----");
                }
                System.out.println();
            }
        }

        result.put("msg","success");
        return result;
    }

}
